package towers;

import gui.Guimap;

import java.lang.reflect.InvocationTargetException;
import java.util.HashSet;
import java.util.Observable;
import java.util.Set;
import java.util.Map.Entry;

import main.Coord;
import main.TDMap;
import main.Tickable;
import runner.Enemy;
import buffs.Buff;

public class Tower extends Observable implements Tickable{
	private Coord pos;
	private Coord gridpos;
	private TDMap map;
	private TowerTemplate tt;
	private int cooldown;
	
	public Tower(TowerTemplate t) {
		tt = t;
	}
	public Tower() {
	}
	public void place(Coord pos, TDMap map) {
		this.pos = pos;
		this.map = map;
		gridpos = pos.clone();
		gridpos.convert(Guimap.TILE_WIDTH, Guimap.TILE_HEIGHT);
	}

	@Override
	public void tick() {
		if (cooldown != 0) {
			cooldown--;
			return;
		}
		Set<Enemy> enem = map.getEnemies();
		for (Enemy e: enem) {
			Coord c = e.getPos();
			if (gridpos.distanceTo(c) <= tt.range) {
				
				Set<Buff> buffs = new HashSet<Buff>();
				for (Entry<Class<? extends Buff>, String> entry: tt.buffs.entrySet()) {
					Buff b=null;
					try {
						b = entry.getKey().getConstructor(String.class).newInstance(entry.getValue());
					} catch (Exception except) {
						except.printStackTrace();
					}
					buffs.add(b);
				}
				
				Projectile p = new Projectile(gridpos.clone(), e, tt.power, buffs);
				map.addProjectile(p);
				
				cooldown=tt.reload;
				return;
			}
		}
	}

	public String toString() {
		return pos +"t";
	}
	
	public TowerTemplate getTemplate() {
		return tt;
	}
	public void upgrade(TowerTemplate temp) {
		tt = temp;
	}

}
